package cn.sykj.car.controller;


import cn.sykj.car.common.ResponseBean;
import cn.sykj.car.common.StatusCode;
import cn.sykj.car.entity.*;
import cn.sykj.car.exception.ParameterInvalidException;
import cn.sykj.car.service.IMenuOperationConfigService;
import cn.sykj.car.service.IMenuService;
import cn.sykj.car.service.IUserRoleService;
import cn.sykj.car.service.IUsersService;
import cn.sykj.car.utils.Utils;
import cn.sykj.car.vo.SysMenuVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 菜单 前端控制器
 * </p>
 *
 * @author Yixu
 * @since 2018-11-29
 */
@Api(hidden = false, tags = {"菜单 前端控制器"})
@RestController
@Slf4j
@RequestMapping("/menu")
public class MenuController extends BaseController{


    @Resource
    private IMenuService iMenuService;

    @Resource
    private IUsersService iUsersService;

    @Resource
    private IUserRoleService iUserRoleService;

    @Resource
    private IMenuOperationConfigService iMenuOperationConfigService;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    /**
     * 添加菜单：登陆后才能操作
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(hidden = false, value = "添加菜单", notes = "登陆才能操作")
    @ApiImplicitParams({

    })
    @RequiresAuthentication
    @RequiresPermissions("menu:create")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ResponseBean insertMenu(
            @RequestBody SysMenuVO menuParam,HttpServletRequest request
    ) throws Exception {

        // 获取登陆系统用户名，存入日志
        Object obj = SecurityUtils.getSubject().getPrincipal();
        log.debug((String) obj);

        // 插入菜单
        this.writeLog("新增菜单");
        return new ResponseBean(StatusCode.OK,iMenuService.insertMenu(menuParam));
    }


    /**
     * 修改菜单：登陆后才能操作
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(hidden = false, value = "修改菜单", notes = "登陆才能操作")
    @RequiresAuthentication
    @RequiresPermissions("menu:edit")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public ResponseBean updateMenu(
            @RequestBody SysMenuVO menuParam,HttpServletRequest request
    ) throws Exception {

        // 获取登陆系统用户名，存入日志
        Object obj = SecurityUtils.getSubject().getPrincipal();
        log.debug((String) obj);



        if (Utils.notEmpty(menuParam.getId())) {

            this.writeLog("修改菜单");
            return new ResponseBean(StatusCode.OK,iMenuService.updateMenu(menuParam));
        } else {
            return new ResponseBean(StatusCode.NOT_FOUND, null);
        }

    }

    /**
     * 删除菜单：登陆后才能操作
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(hidden = false, value = "删除菜单", notes = "登陆才能操作")
    @RequiresAuthentication
    @RequiresPermissions("menu:delete")
    @RequestMapping(value = "/{id}/delete", method = RequestMethod.POST)
    public ResponseBean deleteMenu(
            @PathVariable Integer id,
            HttpServletRequest request) throws Exception {

        // 获取登陆系统用户名，存入日志
        Object obj = SecurityUtils.getSubject().getPrincipal();
        log.debug((String) obj);

        this.writeLog("删除菜单");

        if (Utils.notEmpty(id)) {

            // 删除菜单
            Menu nMenu = new Menu();
            nMenu.setId(id);
            return new ResponseBean(StatusCode.OK,iMenuService.deleteMenu(nMenu));
        } else {
            return new ResponseBean(StatusCode.NOT_FOUND, null);
        }

    }


    /**
     * 查看菜单：登陆后才能操作
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(hidden = false, value = "查看菜单", notes = "登陆才能操作")
    @RequiresAuthentication
    @RequiresPermissions("menu:view")
    @RequestMapping(value = "/selectMenu", method = RequestMethod.POST)
    public ResponseBean selectMenu(
            @RequestBody Menu menuParam) throws Exception {

        // 获取登陆系统用户名，存入日志
        Object obj = SecurityUtils.getSubject().getPrincipal();
        log.debug((String) obj);

        if (Utils.notEmpty(menuParam.getId())) {

            // 查询单条菜单
            Menu nMenu = new Menu();
            nMenu.setId(menuParam.getId());
            return new ResponseBean(StatusCode.OK, iMenuService.selectOneMenu(nMenu));
        } else {

            // 查询全部菜单
            return new ResponseBean(StatusCode.OK, iMenuService.selectAllMenu());
        }

    }

    /**
     * 根据登陆用户id查询菜单
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(hidden = false, value = "根据登陆用户id查询菜单", notes = "登陆才能操作")
    @RequiresAuthentication
    @RequiresPermissions("menu:view")
    @RequestMapping(value = "/selectMenusByUserId", method = RequestMethod.POST)
    public ResponseBean selectMenusByRoleId() {

        // 获取登陆系统用户名，存入日志
        Object obj = SecurityUtils.getSubject().getPrincipal();
        log.debug((String) obj);

        String userName = (String)obj;
        if(Utils.notEmpty(userName)){
            Users users = iUsersService.getUserByName((String) obj);

            QueryWrapper<UserRole> userRoleCondition = new QueryWrapper<>();
            userRoleCondition.eq(UserRole.USER_ID,users.getId());
            List<UserRole> userRoles = iUserRoleService.list(userRoleCondition);
            List<Integer> userRoleIds = new ArrayList<>();
            for(UserRole userRole:userRoles){
                userRoleIds.add(userRole.getRoleId());
            }
            return new ResponseBean(StatusCode.OK, iMenuService.selectMenusByRoleIds(userRoleIds));
        }else{
            return new ResponseBean(HttpStatus.UNAUTHORIZED, 401, "Unauthorized", "");
        }

    }


    /**
     * 查看二级和三级菜单
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(hidden = false, value = "查看二级和三级菜单", notes = "登陆才能操作")
    @RequiresAuthentication
    @RequiresPermissions("menu:view")
    @RequestMapping(value = "/selectSecondMenuAndThirdMenu", method = RequestMethod.POST)
    public ResponseBean selectSecondMenuAndThirdMenu(
            @RequestBody SysMenuVO menuParam) throws Exception {

        // 获取登陆系统用户名，存入日志
        Object obj = SecurityUtils.getSubject().getPrincipal();
        log.debug((String) obj);

        Users sysUsers = iUsersService.getUserByName((String)obj);


        List<Roles> rolesList = iUserRoleService.getRolesByUser(sysUsers);
        List<Integer> roleIds = new ArrayList<>();
        for (Roles roles : rolesList) {
            roleIds.add(roles.getId());
        }
        menuParam.setRoleIds(roleIds);

        List<SysMenuVO> list = iMenuService.selectSecondMenuAndThirdMenu(menuParam);

        return new ResponseBean(StatusCode.OK,list);

    }

    /**
     * 查询一级菜单信息
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(hidden = false, value = "查询一级菜单信息", notes = "登陆才能操作")
    @RequiresAuthentication
    @RequiresPermissions("menu:view")
    @RequestMapping(value = "/selectFirstMenu", method = RequestMethod.POST)
    public ResponseBean selectFirstMenu(@RequestBody SysMenuVO sysMenuVO) {

        // 获取登陆系统用户名，存入日志
        Object obj = SecurityUtils.getSubject().getPrincipal();
        log.debug((String) obj);

        Users sysUsers = iUsersService.getUserByName((String)obj);

        List<Roles> rolesList = iUserRoleService.getRolesByUser(sysUsers);
        List<Integer> roleIds = new ArrayList<>();
        for (Roles roles : rolesList) {
            roleIds.add(roles.getId());
        }

        sysMenuVO.setPid(0);
        sysMenuVO.setRoleIds(roleIds);

        List<SysMenuVO> list = iMenuService.selectFirstMenusByRoleIds(sysMenuVO);
        return new ResponseBean(StatusCode.OK,list);

    }


    /**
     * 根据菜单id查单条菜单信息
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(hidden = false, value = "根据菜单id查单条菜单信息", notes = "登陆才能操作")
    @RequiresAuthentication
    @RequiresPermissions("menu:view")
    @RequestMapping(value = "/selectSingleStripMenu", method = RequestMethod.POST)
    public ResponseBean selectSingleStripMenu(
            @RequestBody SysMenuVO sysMenuModelVO

    ) {

        // 获取登陆系统用户名，存入日志
        Object obj = SecurityUtils.getSubject().getPrincipal();
        log.debug((String) obj);


        if (Utils.isEmpty(sysMenuModelVO.getId())){
            throw new ParameterInvalidException();
        }

        Menu sysMenu = iMenuService.getById(sysMenuModelVO.getId());


        return new ResponseBean(StatusCode.OK,sysMenu);

    }



    /**
     * 根据菜单id查单条权限信息
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(hidden = false, value = "根据菜单id查单条菜单信息", notes = "登陆才能操作")
    @RequiresAuthentication
    @RequiresPermissions("menu:view")
    @RequestMapping(value = "/{menuId}/getMenuOperationConfigByMenuId", method = RequestMethod.POST)
    public ResponseBean getMenuOperationConfigByMenuId(
            @PathVariable Long menuId
    ){

        // 获取登陆系统用户名，存入日志
        Object obj = SecurityUtils.getSubject().getPrincipal();
        log.debug((String) obj);

        List<MenuOperationConfig> list = iMenuOperationConfigService.getMenuOperationConfigByMenuId(menuId);
        return new ResponseBean(StatusCode.OK,list);
    }

}
